/*global window: false, soundManager: false*/
/*
 * #depends subsonic-application.js
 */
Ext.regController('Ext.ux.mattgoldspink.subsonic.controllers.Player', {
    playListener: [],
    currentPlaylist: [],
    currentTrackId: undefined,
    volume: undefined,
	shuffle: false,
	repeatMode: 'off',
    setVolume: function(options){
        this.volume = options.value;
        if (Ext.isDefined(this.currentTrackId)) {
            soundManager.setVolume(this.currentTrackId, options.value);
        }
        Ext.each(this.currentPlaylist, function(track){
            track.setVolume(options.value);
        });
    },
    playTracks: function(options) {
        var tracks = options.tracks, startAtTrack = options.startAtTrack;
        this.disposeOfCurrent();
        tracks.each(function(track, index) {
            var id = track.get('id');
			var sound = {
				id: 'music' + id,
				url: Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/stream.view?' + Ext.urlEncode(Ext.ux.mattgoldspink.subsonic.LoginDetails) +'&id='+id,
				autoLoad: false,//(index === startAtTrack),
				autoPlay: false,
				trackdata: track.data,
				onload: this.handleOnLoad,
				onplay: this.handleOnPlay,
				onresume: this.handleOnPlay,
				onpause: this.handleOnPause,
				onfinish: this.handleOnFinish,
				onstop: this.handleOnStop,
				whileplaying: this.handleWhilePlaying,
				volume: this.volume
			};
            if (index === (startAtTrack + 1)){
                this.currentTrackId = 'music' + id;
				this.makeSound(sound).play();
            }
            this.currentPlaylist.push(sound);
        }, this);
    },
	makeSound: function(options) {
		return soundManager.createSound(options);
	},
    disposeOfCurrent: function(){
        Ext.each(this.currentPlaylist, function(track){
            try {
                track.stop();
                track.destruct();
            } catch(e) {
            }
        });
        this.currentPlaylist = [];
    },
    skipInto: function(options) {
        soundManager.setPosition(this.currentTrackId, options.position * 1000);
    },
    resumeCurrent: function(){
        if (Ext.isDefined(this.currentTrackId) && Ext.isDefined(this.currentPlaylist)){
            var current = soundManager.getSoundById(this.currentTrackId);
            if(current.playState === 0) {
                current.play();
            } else {
                current.resume();    
            }
            current.setVolume(this.volume);
        }
    },
    pauseCurrent: function(){
        soundManager.pause(this.currentTrackId);
    },
    stopCurrent: function(){
        soundManager.stop(this.currentTrackId);
    },
    skipCurrent: function() {
        if (Ext.isDefined(this.currentTrackId) && Ext.isDefined(this.currentPlaylist)){
            var current = soundManager.getSoundById(this.currentTrackId);
            if (!current.paused) {
                current.stop();
            }
            this.doOnFinish({
				track: current,
				skipping: true
			});
        }
    },
    skipBackward: function() {
        if (Ext.isDefined(this.currentTrackId) && Ext.isDefined(this.currentPlaylist)){
            // if more than 3 sec in restart song
            var current = soundManager.getSoundById(this.currentTrackId);
            if (current.position /1000 > 3) {
                soundManager.setPosition(this.currentTrackId, 0);
            } else {
                for (var i = 0; i < this.currentPlaylist.length; i++) {
                    var track = this.currentPlaylist[i];
                    if (track === current) {
                        if (i-1 > -1) {
                            var nextTrack = this.currentPlaylist[i-1];
                            soundManager.stop(this.currentTrackId);
                            this.makeSound(nextTrack).play();
                            this.currentTrackId = nextTrack.id;
							return;
                        } else {
                            soundManager.setPosition(this.currentTrackId, 0);
                        }
                    }
                }
            }
        }
    },
    initialise: function() {
        if (soundManager.supported()) {
            soundManager.onplay = this.handleOnPlay;
            soundManager.onpause = this.handleOnPause;
            soundManager.onfinish = this.handleOnFinish;
        }
    },
    handleOnPlay: function(){
        Ext.dispatch({
            controller: 'Ext.ux.mattgoldspink.subsonic.controllers.Player',
            action    : 'doOnPlay',
            item: this
        });
    },
	handleOnLoad: function() {
		//this.play();
	},
    doOnPlay: function(options) {
        Ext.each(this.playListener, function(listener){
            listener.onPlay(options.item);
        });
    },
    handleOnPause: function() {
    
    },
	handleOnStop: function() {
        //window.Ext.ux.Bus.fireEvent('message', 'subsonic.track.stopped', this.options.trackdata);
    },
    doOnFinish: function(options){
		var nextTrack, doneTrack = options.track, skipping = options.skipping;
		if (!skipping && this.repeatMode === 'one') {
			nextTrack = doneTrack;
		} else if (!this.shuffle) {
			for (var i = 0; i < this.currentPlaylist.length; i++) {
				var track = this.currentPlaylist[i];
				if (track.id === doneTrack.sID && i+1 < this.currentPlaylist.length) {
					nextTrack = this.currentPlaylist[i+1];
					break;
				}
			}
			if (nextTrack === undefined && this.repeatMode === 'all') {
				nextTrack = this.currentPlaylist[0];
			}
		} else {
			var total = this.currentPlaylist.length, nextIndex = Math.floor(Math.random()*total);
			nextTrack = this.currentPlaylist[nextIndex];
		}
		if (!doneTrack.paused) {
			if (!skipping || (skipping && doneTrack.playState !== 1)) {
				if (!skipping) {
					this.handleOnStop.apply(doneTrack, []);
				}
				if (nextTrack) {
					this.makeSound(nextTrack).play();
				}
			}
		} else {
			if (doneTrack.playState === 0) {
				this.handleOnStop.apply(doneTrack, []);
			} else {
				doneTrack.stop();
			}
			if (nextTrack) {
				var sound = this.makeSound(nextTrack);
				sound.load();
				sound.pause();
			}
		}
		if (nextTrack) {
			this.currentTrackId = nextTrack.id;
		} else {
			this.currentTrackId = this.currentPlaylist[0].id;
		}
    },
    handleOnFinish: function() {
        Ext.dispatch({
            controller: 'Ext.ux.mattgoldspink.subsonic.controllers.Player',
            action    : 'doOnFinish',
            track: this,
			skipping: false
        });
    },
    handleVolumeChange: function() {
        for (var i = 0; i < this.volume.length; i++) {
            try {
            
            } catch(e) {
                
            }
        }
    },
	doShuffleToggle: function(data) {
		this.shuffle = !this.shuffle;
	},
	handleRepeat: function(data) {
		this.repeatMode = data;
	},
    registerVolumeDisplay: function(options) {
        this.volume.push(options.volume);
    },
    registerPlayListener: function(options) {
        this.playListener.push(options.listener);
    }
});
